#include "TitleBar.h"

#include <core/StyleMgr.h>
#include <widgets/KeySearchWidget.h>
#include <widgets/SImageButton.h>

#include <QApplication>
#include <QBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMouseEvent>
#include <QPropertyAnimation>
#include <QStylePainter>

#include "AppMenu.h"
#include "MainFrame.h"
#include "StatusBar.h"
#include "TabBar.h"

constexpr auto LINE_HEIGTH = 1;

TitleBar::TitleBar(MainFrame* frame, QWidget* parent)
    : QWidget(parent), m_frame(frame), m_canDrag(false) {
  //----------------------------------
  //|              |    righttop     |
  //|	left	     |-----------------|
  //|              |    rightbottom  |
  //|--------------------------------|
  //| bottom                         |
  //----------------------------------
  QVBoxLayout* mainLayout = new QVBoxLayout;
  mainLayout->setContentsMargins(0, 0, 0, 0);
  QGridLayout* gridLayout = new QGridLayout;

  // left
  QHBoxLayout* leftLayout = new QHBoxLayout;
  m_menu = new AppMenu(m_frame, this);
  connect(this, &TitleBar::setCommonPage, m_menu, &AppMenu::onCommonPage);
  leftLayout->addWidget(m_menu);
  m_btnSearch = new SImageButton(this, "guiframe_app_label_search");
  m_btnSearch->setVisible(false);
  leftLayout->addWidget(m_btnSearch);
  m_searchWidget = new KeySearchWidget(this, "SearchBackNormal", "SearchHover",
                                       "BorderNormal", 8, true);
  m_searchWidget->setAutoKillFocus(true);
  m_searchWidget->setFixedSize(320, 32);
  m_searchWidget->setPromptText(tr("搜索证券、公司和功能代码"));
  m_searchWidget->setResultDlgMinWidth(380);
  m_searchWidget->setResultDlgMaxHeight(ITEM_DEFAULT_HEIGHT * 8);
  m_searchWidget->setColumnsWidth(4, 120, 150, 50, 50);
  leftLayout->addWidget(m_searchWidget, 0, Qt::AlignVCenter);
  gridLayout->addItem(leftLayout, 0, 0);

  // right
  QVBoxLayout* rightLayout = new QVBoxLayout;
  // right top
  QHBoxLayout* rightTop = new QHBoxLayout;
  rightTop->addStretch();
  m_btnMin = new SImageButton(this, "guiframe_app_min");
  m_btnMin->setToolTip("最小化");
  // m_btnMin->setStyleSheet("QToolTip{border:1px solid #308376;font:12px
  // Microsoft
  // YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235,
  // 200)}");
  rightTop->addWidget(m_btnMin);
  m_btnRestore = new SImageButton(this, "guiframe_app_restore");
  m_btnRestore->setToolTip("还原");
  // m_btnRestore->setStyleSheet("QToolTip{border:1px solid #308376;font:12px
  // Microsoft
  // YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235,
  // 200)}");
  rightTop->addWidget(m_btnRestore);
  m_btnFull = new SImageButton(this, "guiframe_app_full");
  m_btnFull->setToolTip("最大化");
  // m_btnFull->setStyleSheet("QToolTip{border:1px solid #308376;font:12px
  // Microsoft
  // YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235,
  // 200)}");
  rightTop->addWidget(m_btnFull);
  m_btnClose = new SImageButton(this, "guiframe_app_close");
  m_btnClose->setToolTip("关闭");
  // m_btnClose->setStyleSheet("QToolTip{border:1px solid #308376;font:12px
  // Microsoft
  // YaHei;font-weight:bold;background-color:rgb(9,36,36);color:rgb(255, 235,
  // 200)}");
  rightTop->addWidget(m_btnClose);
  if (m_frame->windowState() == Qt::WindowState::WindowMaximized) {
    m_btnFull->setVisible(false);
  } else {
    m_btnRestore->setVisible(false);
  }
  rightLayout->addItem(rightTop);
  // right bottom
  m_statusBar = new StatusBar(nullptr, this);
  m_statusBar->setContentsMargins(0, 0, 80, 0);
  rightLayout->addWidget(m_statusBar);
  gridLayout->addItem(rightLayout, 0, 1);

  // bottom
  m_tabBar = new TabBar(this);
  m_frame->setTabBar(m_tabBar);
  QHBoxLayout* tabLayout = new QHBoxLayout;
  tabLayout->setContentsMargins(10, 0, 0, 0);
  tabLayout->addWidget(m_tabBar);
  gridLayout->addLayout(tabLayout, 1, 0, 1, 2);
  mainLayout->addItem(gridLayout);
  setLayout(mainLayout);

  connect(m_btnClose, &SImageButton::clicked, m_frame, &QWidget::close);
  connect(m_btnMin, &SImageButton::clicked, this, &TitleBar::onBtnClicked);
  connect(m_btnFull, &SImageButton::clicked, this, &TitleBar::onBtnClicked);
  connect(m_btnRestore, &SImageButton::clicked, this, &TitleBar::onBtnClicked);
  connect(m_btnSearch, &SImageButton::clicked, this, &TitleBar::onBtnClicked);
  connect(m_tabBar, &TabBar::requestResize, this, &TitleBar::onTabNeedResize);
  connect(m_searchWidget, &KeySearchWidget::resultHide, this,
          &TitleBar::onSearchResultHide);

  m_animation = new QPropertyAnimation(this, "animateProgess");
  m_animation->setDuration(100);
  connect(m_animation, &QPropertyAnimation::finished, this,
          &TitleBar::onAnimationFinished);

  setFocusProxy(m_searchWidget);
}

TitleBar::~TitleBar() { qApp->removeEventFilter(this); }

void TitleBar::showSearch() {
  if (m_btnSearch->isHidden()) return;
  startResizeAnimation(true);
}

void TitleBar::paintEvent(QPaintEvent* event) {
  QRect rc = rect();
  QStylePainter painter(this);
  painter.fillRect(rc, NAME_COLOR("MainTitleBack"));

  QPoint pos = m_tabBar->pos();
  rc.setTop(pos.y());
  painter.fillRect(rc, NAME_COLOR("ElementBackground"));

  // QPen pen(QColor(0xFF, 0x93, 0), LINE_HEIGTH);
  // painter.setPen(pen);
  // painter.drawLine(0, rect().height() - LINE_HEIGTH, rect().width(),
  // rect().height() - LINE_HEIGTH);
}

void TitleBar::mousePressEvent(QMouseEvent* e) {
  m_lastMPos = e->globalPos();
  m_canDrag = !m_menu->geometry().contains(e->pos());
}

void TitleBar::mouseReleaseEvent(QMouseEvent* event) {
  setCursor(Qt::CursorShape::ArrowCursor);
  m_canDrag = false;
}

void TitleBar::mouseDoubleClickEvent(QMouseEvent* event) {
  maximizeMainFrame(m_frame->windowState() != Qt::WindowState::WindowMaximized);
}

void TitleBar::mouseMoveEvent(QMouseEvent* e) {
  QPoint spos = e->globalPos() - m_lastMPos;
  if (m_canDrag && spos.manhattanLength() > 5) {
    setCursor(Qt::CursorShape::SizeAllCursor);
    m_frame->move(m_frame->pos() + spos);
    m_lastMPos = e->globalPos();
  }
}

void TitleBar::resizeEvent(QResizeEvent* event) {
  if (m_tabBar) onTabNeedResize(m_tabBar->tabShrinked() ? 0 : 1);
}

void TitleBar::maximizeMainFrame(bool max) {
  if (max) {
    m_frame->setWindowState(Qt::WindowState::WindowMaximized);
  } else {
    m_frame->setWindowState(Qt::WindowState::WindowNoState);
  }

  m_btnFull->setVisible(!max);
  m_btnRestore->setVisible(max);
}

void TitleBar::onBtnClicked() {
  if (sender() == m_btnMin) {
    m_frame->setWindowState(Qt::WindowState::WindowMinimized);
  } else if (sender() == m_btnFull) {
    maximizeMainFrame(true);
  } else if (sender() == m_btnRestore) {
    maximizeMainFrame(false);
  } else if (sender() == m_btnSearch) {
    startResizeAnimation(true);
  }
}

void TitleBar::setProgress(int p) {
  m_searchWidget->setFixedWidth(p * 200 / 100);
}

void TitleBar::startResizeAnimation(bool showSearch) {
  if (showSearch) {
    m_btnSearch->hide();
    m_searchWidget->setEnabled(true);
    m_searchWidget->setFixedWidth(0);
    m_searchWidget->setFocus();
    m_animation->setStartValue(0);
    m_animation->setEndValue(100);
  } else {
    m_btnSearch->show();
    m_animation->setStartValue(100);
    m_animation->setEndValue(0);
  }
  m_animation->start();
}

void TitleBar::onTabNeedResize(int type) {
  if (type == 1) {
    if (!m_searchWidgetHide ||
        m_tabBar->leftSpace() < 200)  // 200：width of the search edit
      return;
  } else if (m_searchWidgetHide == true)
    return;

  m_searchWidgetHide = type == 0;
  startResizeAnimation(!m_searchWidgetHide);
}

void TitleBar::onSearchResultHide() {
  if (m_searchWidgetHide) {
    startResizeAnimation(false);
  }
}

void TitleBar::onAnimationFinished() {
  update();
  if (m_btnSearch->isVisible())
    m_searchWidget->setDisabled(true);  // not receive keyboard event
}

void TitleBar::onCommonPage(int* ids, int size, int ntype) {
  setCommonPage(ids, size, ntype);
}